import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import {
  Card,
  message,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Modal,
  Spin,
  Divider,
  Table,
  Descriptions,
} from 'antd';
import MyPageTable from '@/components/MyPageTable';
import { onTableData } from '@/utils/utils.js';
import CopyToClipboard from '@/components/CopyToClipboard';
import { getTimeDistance } from '@/utils/utils';
import moment from 'moment';
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
import MotionService from './services';
import SearchItemEnum from "@/components/Search/SearchItemEnum";
const auditState = ['审核中', '审核拒绝', '审核通过'];
@connect(({ order, loading }) => ({
  ...order,
  loading: loading.effects['order/queryOpeOrderByConditionList'],
}))
@Form.create()
export default class Order extends Component {
  state = {
    current: 1,
    visible: false,
    orderId: null,
    datas: {},
    auditVisible: false,
    AuditDetail: [],
    Pageloading: false,
    list: [],
    total: 1,
    deliverOptions: [],
    title: '发货',
    refuseData: '',
  };
  auditColumns = [
    {
      title: '审核时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
    },
    {
      title: '审核人员',
      dataIndex: 'operator',
      width: 120,
    },
    {
      title: '审核结果',
      dataIndex: 'auditStatus',
      width: 120,
      render: text => {
        const _text = auditState[text];
        if (text === 1) {
          return (
            <span className="red">
              <Badge status="error" />
              未通过
            </span>
          );
        }
        return _text;
      },
    },
    {
      title: '反馈详情',
      dataIndex: 'feedBack',
    },
  ];
  componentDidMount() {
    this.onList(1, 10);
    MotionService.selectExpressList().then(res => {
      this.setState({
        deliverOptions: res,
      });
    });
  }

  onList = (pageNumber, pageSize, data = {}) => {
    this.setState({
      Pageloading: true,
    });
    MotionService.exchangeOrderPage({ pageNumber, pageSize, ...data }).then(res => {
      this.setState({
        Pageloading: false,
        list: res.records || [],
        total: res.total,
      });
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (values.createDate && values.createDate.length < 1) {
        values.createTimeBegin = '';
        values.createTimeEnd = '';
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            this.onList(1, 10, { ...values });
          },
        );
      } else if (values.createDate) {
        values.createTimeBegin = moment(values.createDate[0]).format('YYYY-MM-DD HH:mm:ss');
        values.createTimeEnd = moment(values.createDate[1]).format('YYYY-MM-DD HH:mm:ss');
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            this.onList(1, 10, { ...values });
          },
        );
      } else {
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            this.onList(1, 10, { ...values });
          },
        );
      }
    });
  };

  handleOk = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { orderId, title } = this.state;
        if (title === '发货') {
          MotionService.exchangeOrderDelivery({
            expressId: values.expressId,
            expressNo: values.expressNo,
            orderId,
          }).then(res => {
            this.setState({
              visible: false,
            });
            message.success('发货成功～');
            this.onList(1, 10);
          });
        } else {
          MotionService.exchangeOrderRefuse({
            resfuseResaon: values.resfuseResaon,
            orderId,
          }).then(res => {
            this.setState({
              visible: false,
            });
            message.success('成功～');
            this.onList(1, 10);
          });
        }
      }
    });
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };
  //table 页数
  onPage = e => {
    this.setState(
      {
        current: e.current,
      },
      () => {
        this.onList(e.current, 10, this.state.datas);
      },
    );
  };
  close = () => {
    this.setState({
      auditVisible: false,
    });
  };
  handleAuditModal = orderId => {
    this.setState(
      {
        auditVisible: true,
        orderId,
      },
      () => {
        MotionService.exchangeOrderRefuseReason({ orderId }).then(res => {
          this.setState({
            refuseData: res,
          });
        });
      },
    );
  };
  handleModal = (e, orderId) => {
    this.setState({
      visible: true,
      title: e,
      orderId,
    });
  };
  
  handleReset = e => {
    this.props.form.resetFields();
    this.onList(1, 10);
    this.setState({
      current: 1,
    });
  };
  
  render() {
    const {
      auditVisible,
      AuditDetail,
      Pageloading,
      total,
      list,
      deliverOptions,
      title,
      refuseData,
    } = this.state;
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: total,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      ),
    };
    const Status = {
      DEALING: '兑换中',
      WAITING_RECEIVE: '已发货',
      REFUSED: '已拒绝',
      FINISHED: '已完成',
    };
    const columns = [
      {
        title: '兑换订单号',
        dataIndex: 'orderId',
        width: '10%',
        render: orderId => <CopyToClipboard text={orderId} />,
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
        width: '10%',
      },
      {
        title: '下单人姓名/手机号',
        width: '20%',
        render: e => `${e.userName} / ${e.telephone}`,
      },
      {
        title: '销售原价',
        dataIndex: 'salePrice',
        width: '10%',
      },

      {
        title: '点券',
        dataIndex: 'exchangePoint',
        width: '10%',
      },
      {
        title: '兑换时间',
        dataIndex: 'createTime',
        width: '15%',
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: status => Status[status],
      },
      {
        title: '操作',
        width: '15%',
        align: 'center',
        render: e => {
          return (
            <div>
              <a
                href={`#/Motion/Order/OrderDetails?orderId=${e.orderId}`}
                style={{ cursor: 'pointer', color: '#3F66F5' }}
                target="_blank"
              >
                查看
              </a>
              {e.status === 'DEALING' ? (
                <>
                  <Divider type="vertical" />
                  <span
                    style={{ cursor: 'pointer', color: '#3F66F5' }}
                    onClick={() => this.handleModal('发货', e.orderId)}
                  >
                    发货
                  </span>
                </>
              ) : null}
              {e.status === 'REFUSED' ? (
                <div>
                  <span
                    style={{ cursor: 'pointer', color: '#3F66F5' }}
                    onClick={() => this.handleAuditModal(e.orderId)}
                  >
                    拒绝详情
                  </span>
                </div>
              ) : null}
              {e.status === 'DEALING' ? (
                <div>
                  <span
                    style={{ cursor: 'pointer', color: '#3F66F5' }}
                    onClick={() => this.handleModal('拒绝兑换', e.orderId)}
                  >
                    拒绝兑换
                  </span>
                </div>
              ) : null}
            </div>
          );
        },
      },
    ];
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Form layout="inline" onSubmit={this.handleSubmit} style={{ marginBottom: 20 }}>
            <Form.Item label={'状态'}>
              {getFieldDecorator(
                'status',
                {},
              )(
                <Select placeholder="状态" style={{ width: 180 }}>
                  <Option value="">全部</Option>
                  <Option value="DEALING">兑换中</Option>
                  <Option value="WAITING_RECEIVE">已发货</Option>
                  <Option value="REFUSED">已拒绝</Option>
                  <Option value="FINISHED">已完成</Option>
                </Select>,
              )}
            </Form.Item>
            { SearchItemEnum['productName'](getFieldDecorator) }
            <Form.Item label={'创建时间'}>
              {getFieldDecorator(
                'createDate',
                {},
              )(<RangePicker placeholder={['下单开始时间', '下单结束时间']} />)}
            </Form.Item>
            { SearchItemEnum['orderer'](getFieldDecorator) }
            { SearchItemEnum['ordererPhone'](getFieldDecorator) }
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
            <Form.Item>
              <Button htmlType="button" onClick={this.handleReset}>
                重置
              </Button>
            </Form.Item>
          </Form>
          <Spin spinning={Pageloading}>
            <MyPageTable
              onPage={this.onPage}
              paginationProps={paginationProps}
              dataSource={onTableData(list)}
              columns={columns}
            />
          </Spin>
        </Card>
        <Modal
          title={title}
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          destroyOnClose
        >
          {title === '发货' ? (
            <Form>
              <Form.Item>
                {getFieldDecorator(
                  'expressId',
                  {},
                )(
                  <Select style={{ width: '100%' }} placeholder="请选择物流公司">
                    {deliverOptions.map(option => {
                      return (
                        <Option key={option.id} value={option.id}>
                          {option.name}
                        </Option>
                      );
                    })}
                  </Select>,
                )}
              </Form.Item>
              <Form.Item>
                {getFieldDecorator('expressNo', {})(<Input placeholder="请输入物流单号" />)}
              </Form.Item>
            </Form>
          ) : (
            <Form>
              <Form.Item label="拒绝原因" {...formItemLayout}>
                {getFieldDecorator('resfuseResaon', {
                  rules: [{ required: true, message: '请输入' }],
                })(<TextArea placeholder="请输入" rows={4} />)}
              </Form.Item>
            </Form>
          )}
        </Modal>
        <Modal
          title="拒绝详情"
          visible={auditVisible}
          footer={null}
          onCancel={this.close}
          destroyOnClose
          // width={900}
        >
          {/* <Card bordered={false}>
            <Table
              rowKey="id"
              columns={this.auditColumns}
              dataSource={AuditDetail}
              pagination={{
                current: 1,
                total: 10,
                // onChange: this.onChange,
                // showTotal: this.showTotal,
                // showQuickJumper: true,
                // pageSizeOptions: ['5', '10', '20'],
                // showSizeChanger: true,
                // onShowSizeChange: this.onShowSizeChange,
              }}
            />
          </Card> */}
          <Descriptions>
            <Descriptions.Item label="拒绝原因">{refuseData}</Descriptions.Item>
          </Descriptions>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
